#define _CRT_SECURE_NO_WARNINGS 1
#include "LinkList.h"

void Initlist(pLinkList *head)
{
	*head = NULL;
}

void PushBack(pLinkList *head,Datatype d)
{
	LinkList *p = *head;
	LinkList *New = malloc(sizeof(LinkList));
	if (NULL == New)
	{
		perror("::");
		exit(EXIT_FAILURE);
	}
	New->data = d;
	New->next = NULL;
	if (NULL == p)
	{
		*head = New;
		return ;
	}
	while (p->next)
	{
		p = p->next;
	}
	p->next = New;
}

void Display(LinkList *head)
{
	LinkList *p = head;
	if (NULL == p)
	{
		return ;
	}
	while (p)
	{
		printf("%d-->",p->data);
		p = p->next;
	}
	printf("\n");
}


int FindKList(LinkList *head,int k)
{
	LinkList *fast = head;
	LinkList *slow = head;
	LinkList *p = head;
	if (NULL == p)
	{
		printf("NO data!");
		exit(EXIT_FAILURE);
	}
	while (k--&&fast)
	{
		fast = fast->next;
	}
	while (fast)
	{
		fast = fast->next;
		slow = slow->next;
	}
	return slow->data;
}
void PushFront(pLinkList *head,Datatype d)
{
	//LinkList *p = *head;
	LinkList *New = malloc(sizeof(LinkList));
	if (NULL == New)
	{
		perror("::");
		exit(EXIT_FAILURE);
	}
	New->data = d;
	New->next = NULL;
	if (*head == NULL)
	{
		*head = New;
		return ;
	}
	New->next = *head;
	*head = New;
}


int JudegeClock(pLinkList *head)
{
	LinkList *fast = *head;
	LinkList *slow = fast;
	LinkList *p = *head;
	if (NULL == p)
	{
		return 0;
	}
	while (fast&&fast->next)
	{
		fast = fast->next->next;
		slow = slow->next;
		if (fast == slow)
		{
			return 1;
		}
	}
	return 0;
}


void MakeListToLoop(pLinkList *head)
{
	LinkList *p = *head;
	if (NULL == p)
	{
		return ;
	}
	while (p->next)
	{
		p = p->next;
	}
	p->next = *head;
}



LinkList *FindKdata(pLinkList *head,Datatype k)
{
	LinkList *p = *head;
	while (p)
	{
		if (p->data == k)
		{
			return p;
		}
		p = p->next;
	}
	return NULL;
}


void IntersectList(pLinkList *head,pLinkList *head1)
{
	LinkList *p = *head;
	LinkList *p1 = *head1;
	LinkList *ret = NULL;
	ret = FindKdata( head,5);
	if (NULL == p1)
	{
		*head1 = ret;
	}
	while (p1->next)
	{
		p1 = p1->next;
	}
	p1->next = ret;
}


int ListLong(pLinkList *head)
{
	LinkList *p = *head;
	int count = 0;
	while (p)
	{
		count++;
		p = p->next;
	}
	return count;
}

LinkList *JudegeIntersect(pLinkList *head,pLinkList *head1)
{
	LinkList *p = *head;
	LinkList *p1 = *head1;
	size_t Lhead = ListLong(head);
	size_t Lhead1 = ListLong(head1);
	int sz = Lhead-Lhead1;
	if (Lhead>Lhead1)
	{
		while (sz--)
		{
			p = p->next;            //can't put judge in while!!!
		}
	}
	else
	{
		while (sz--)
		{
			p1 = p1->next;
		}
	}
	while (p)
	{
		if (p == p1)
		{
			return p;
		}
		p = p->next;
		p1 = p1->next;
	}
	return NULL;
}

void DistoryList(pLinkList * head)
{
	LinkList *p = *head;
}